class simplePromise {
  constructor(excutor) {
    this.status = 'pending' // 初始状态为pending、fulfilled、rejected
    this.value = undefined // 成功时的返回值
    this.reason = undefined // 失败时的返回值
    this.onFulfilledCallbacks = [] // 成功时的回调函数数组
    this.onRejectedCallbacks = [] // 失败时的回调函数数组

    const resolve = (value) => {
      if (this.status === 'pending') {
        this.status = 'fulfilled'
        this.value = value
        this.onFulfilledCallbacks.forEach(fn => fn(this.value))
      }
    }
    const reject = (reason) => {
      if (this.status === 'pending') {
        this.status = 'rejected'
        this.reason = reason
        this.onRejectedCallbacks.forEach(fn => fn(this.reason))
      }
    }

    try {
      excutor(resolve, reject)
    } catch (error) {
      reject(error)
    }
  }

  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }

    return new simplePromise((resolve, reject) => {
      const handleFulfilled = () => {
        try {
          const result = onFulfilled(this.value)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      }
      const handleRejected = () => {
        try {
          const result = onRejected(this.reason)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      }

       if (this.status === 'fulfilled') {
        handleFulfilled()
      } else if (this.status === 'rejected') {
        handleRejected()
      } else if (this.status === 'pending') {
        this.onFulfilledCallbacks.push(handleFulfilled)
        this.onRejectedCallbacks.push(handleRejected)
      }
    })
  }
}
